package com.xywy.wjk;

import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.xywy.R;
import com.xywy.common.BaseActivity;
import com.xywy.common.app.MainApplication;
import com.xywy.common.bean.ConnectedDevice;
import com.xywy.common.greendao.BaseDao;
import com.xywy.common.util.FileUtil;
import com.xywy.common.util.ble.util.BLEWeightScaleProvider;
import com.xywy.me.bean.User;
import com.xywy.me.bean.UserKeeper;
import com.xywy.wjk.adapter.WeightDetailAdapter;
import com.xywy.wjk.bean.WeightData;
import com.xywy.wjk.bean.WeightDetail;
import com.xywy.wjk.dao.WeightDataDao;
import com.xywy.wjk.dao.WeightDataDao.Properties;
import com.xywy.wjk.util.WjkConstant;
import com.xywy.wjk.widget.MyZxView;

import de.greenrobot.dao.query.QueryBuilder;

/**
 * @ClassName: WjkDetailActivity
 * @Description: 云健康体重详情页
 * 
 * @author ZhiluCui
 * @date 2014年10月13日 下午8:12:24
 * @version:1.0
 */
public class WjkDetailActivity extends BaseActivity implements OnClickListener {
	private static final String TAG = "WjkDetailActivity";
	private Context mContext;
	private RelativeLayout rlBack;

	private byte[] currentUserWeightData1; // 当前用户重量数据1，
	private byte[] currentUserWeightData2; // 当前用户重量数据2

	private ListView lv_tz_data;
	private TextView tv_wjk_detail_weight;

	private ArrayList<WeightDetail> mListViewWeightDetail = new ArrayList<WeightDetail>();
	private BLEWeightScaleProvider weightScaleProvider;

	private WeightDetail weightDetail;

	private MyZxView myZxView;// 折线图
	private List<Integer> weightData = new ArrayList<Integer>();

	private TextView dayTv, mounthTv, yearTv, weekTv;
	private RelativeLayout rl_wjk_weight_detail;
	private RelativeLayout rl_wjk_detail_back;

	private TextView historyLow; // 历史最低
	private TextView lastDiff; // 与上次比较
	private TextView historyHeigh;// 历史最高
	private TextView tv_add_device;// 添加设备
	private User current_user;
	

	private int temp2; // 表示wjk页面当前的fragment为 10 体重 ， 11 血压；（不确定是否连接）
	Handler handler = new Handler() {
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置为全屏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.wjk_detail);
		this.initDAO();
		this.preInit();
		this.initView();
		this.loadData();

	}

	@Override
	protected void onResume() {
		super.onResume();
		/* 将页面其实位置定位在头部； */
		setNoData();
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				runOnUiThread(new Runnable() {
					public void run() {
						ll_wjk_detail.scrollTo(0, 0);
					}
				});
			}
		}, 10);
	}

	private void setNoData() {
		WeightData flagData = getLastWeightData();
		if (flagData == null) {
			historyLow.setText(0 + "");
			DecimalFormat df = new DecimalFormat("0.0");
			float offset = Float.parseFloat(df.format(getLastData()));
			String temp = "";
			if (offset > 0) {
				temp = "+";
			} else {
				temp = "";
			}
			tv_wjk_detail_tx.setText("");
			lastDiff.setText(temp + df.format(getLastData()));
			tv_wjk_detail_weight.setText("0");
			historyHeigh.setText(getMinWeight() + "");
			myZxView.setGaveWorth(getDayAgoData(), MyZxView.MODE_DAY);

			List<WeightDetail> listdetails = new ArrayList<WeightDetail>();
			for (int i = 0; i < 9; i++) {
				WeightDetail data = new WeightDetail();
				data.setItemIcon(ItemIcon[i]);
				data.setItemName(ItemName[i]);
				data.setItemValue(0f);
				data.setItemValueRate(ItemValueRate[i]);
				data.setItemState("");
				//
				listdetails.add(data);
			}
			WeightDetailAdapter adapter = new WeightDetailAdapter(listdetails,
					this);
			lv_tz_data.setAdapter(adapter);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();

	}

	float weight; // 体重
	float fatData; // 脂肪
	float waterData; // 水分
	float boneData; // 骨骼
	float fatUnderSkin;// 皮下脂肪
	float Metabolisim; // 基础代谢
	float fatInBody;// 体内脂肪
	float muscleData; // 肌肉
	float BodyAge;// 身体年龄
	Date date;// 当前时间
	SharedPreferences sp;
	private MainApplication app;

	private TextView tv_detail_data_state;

	private TextView tv_wjk_detail_tx;

	private float height;

	private WeightData weightDataTemp;

	@Override
	public void preInit() {
		current_user = UserKeeper.getCurrentUser(this);
		MainApplication.addSpeciall(this);
		sp = getSharedPreferences("config", Context.MODE_PRIVATE);
		height = sp.getInt("height", 170);
		Log.e(TAG + "dddd", height + "");
		Intent intent = getIntent();
		weightDataTemp = getLastWeightData();
		if (weightDataTemp != null){
			weight = weightDataTemp.getWeight();
			fatData = weightDataTemp.getFatData();
			waterData = weightDataTemp.getWaterData();
			boneData = weightDataTemp.getBoneData();
			fatUnderSkin = weightDataTemp.getFatUnderSkin();
			Metabolisim = weightDataTemp.getMetabolisim();
			
			fatInBody = weightDataTemp.getFatInBody();
			muscleData = weightDataTemp.getMuscleData();
			BodyAge = weightDataTemp.getBodyAge();
		}
		mContext = this.context;
	}

	/**
	 * 当前页面体重连接的一个显示隐藏情况；
	 */
	private void connectBtnState() {
//		weightScaleProvider = MainApplication.getInstance()
//				.getWeightBleProvider();
//		temp2 = sp.getInt("curFrag", -2);
		ConnectedDevice weight_device = FileUtil.getWeightDevice();
		if (weight_device.isConnected()) {
//			if (temp2 == 11)// 如果当前页面是血压
//			{
//				tv_add_device.setVisibility(View.VISIBLE);
//			} else
				tv_add_device.setVisibility(View.GONE);
		} else {
//			tv_add_device.setVisibility(View.VISIBLE);
				tv_add_device.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void loadData() {
		// 这个时候显示给填充一些家的数据
		app = MainApplication.getInstance();
		connectBtnState();
		WeightData data[] = getDayAgoData();
		historyLow.setText(getMaxWeight() + "");
		DecimalFormat df = new DecimalFormat("0.0");
		float offset = Float.parseFloat(df.format(getLastData()));
		String temp = "";
		if (offset > 0) {
			temp = "+";
		} else {
			temp = "";
		}
		lastDiff.setText(temp + df.format(getLastData()));

		historyHeigh.setText(getMinWeight() + "");
		myZxView.setGaveWorth(data, MyZxView.MODE_DAY);
	}

	ScrollView ll_wjk_detail;

	final int[] ItemIcon = new int[] { R.drawable.tz_detail_data_bmi,
			R.drawable.tz_detail_data_stnl, R.drawable.tz_detail_data_zfl,
			R.drawable.tz_detail_data_jrl, R.drawable.tz_detail_data_shl,
			R.drawable.tz_detail_data_jcdx, R.drawable.tz_detail_data_ggzl,
			R.drawable.tz_detail_data_pxzf, R.drawable.tz_detail_data_nzzf };

	// // bmi 体质量指数
	final String[] ItemName = new String[] { "BMI", "身体年龄", "脂肪率", "肌肉率",
			"水含量", "基础代谢", "骨骼重量", "皮下脂肪", "内脏脂肪" };

	String[] ItemValueRate = new String[] { "", "", "%", "%", "%", "", "", "",
			"", };

	@Override
	public void initView() {
		tv_add_device = (TextView) findViewById(R.id.tv_add_device);
		tv_add_device.setOnClickListener(this);
		ll_wjk_detail = (ScrollView) findViewById(R.id.ll_wjk_detail);
		tv_detail_data_state = (TextView) findViewById(R.id.tv_detail_data_state);
//		llChart = (LinearLayout) findViewById(R.id.ll_wjk_detail_chart);
		tv_wjk_detail_weight = (TextView) findViewById(R.id.tv_wjk_detail_weight);
		TextPaint textPaint = tv_wjk_detail_weight.getPaint();
		textPaint.setFakeBoldText(true);
		tv_wjk_detail_tx = (TextView) findViewById(R.id.tv_wjk_detail_tx);

		lv_tz_data = (ListView) findViewById(R.id.lv_tz_data);
		//
		myZxView = (MyZxView) findViewById(R.id.tableline);//
		historyLow = (TextView) findViewById(R.id.historyLow);
		lastDiff = (TextView) findViewById(R.id.lastDiff);
		historyHeigh = (TextView) findViewById(R.id.historyHeigh);

		if (weightDataTemp != null) {
			tv_wjk_detail_weight.setText(weightDataTemp.getWeight() + "");
			if (weightDataTemp.getWeight() < Math.pow((height / 100.0), 2) * 18.5) {// height
																					// *
																					// height
				tv_wjk_detail_tx.setText("建议增加膳食的摄入量，应丰富多样；多吃高蛋白等食品，加强体育锻炼。");
			} else if (weight > (height / 100.0) * (height / 100.0) * 24) {
				tv_wjk_detail_tx.setText("控制饮食，注意避免油腻的食物，多吃水果蔬菜，多锻炼控制体重。");
			} else {
				tv_wjk_detail_tx.setText("继续保持良好的作息时间和适当锻炼。");
			}
		}
		myZxView.setOnClickListener(this);
		List<Map<String, Object>> mylist = new ArrayList<Map<String, Object>>();
        DecimalFormat df = new DecimalFormat("#.0");
		Date date;// 当前时间
		float bmi = Float.parseFloat(df.format((weight / ((height / 100) * (height / 100)))));
        System.out.println("这是bmi   "+bmi);
        DecimalFormat IntegerDf = new DecimalFormat("#");
		final float[] ItemValue = new float[] { bmi, Math.round(Float.parseFloat(IntegerDf.format(BodyAge))), fatData,
				boneData, waterData, Math.round(Float.parseFloat(IntegerDf.format(Metabolisim))), muscleData, fatUnderSkin,
				fatInBody };
		String[] ItemValueRate = new String[] { "", "", "%", "%", "%", "", "",
				"", "", };
		float age = sp.getInt("age", 0);
		float[] DataLowStandard = { (float) 18.5, age, 13, (float) 49.4,
				(float) 53.6, 1510, (float) 2.4, (float) 8.6, (float) 9.0 };

		float[] DataHighStandard = { 24, age, 21, (float) 59.4, 57, 1510,
				(float) 2.6, (float) 16.7, 15 };

		List<WeightDetail> listdetails = new ArrayList<WeightDetail>();
		for (int i = 0; i < 9; i++) {
			WeightDetail data = new WeightDetail();
			data.setItemIcon(ItemIcon[i]);
			data.setItemName(ItemName[i]);
			data.setItemValue(ItemValue[i]);
			data.setItemValueRate(ItemValueRate[i]);
			if (ItemValue[i] < DataLowStandard[i]) {
				data.setItemState("偏低");

			} else if (ItemValue[i] > DataHighStandard[i]) {
				data.setItemState("偏高");
			} else {
				data.setItemState("正常");
			}
			listdetails.add(data);
			WeightDetailAdapter adapter = new WeightDetailAdapter(listdetails,
					this);
			lv_tz_data.setAdapter(adapter);
		}

		WeightDetailAdapter adapter = new WeightDetailAdapter(listdetails, this);

		// 解决listView与ScrollView 冲突
		int totalHeight = 0;
		System.out.println("这个是listview的高度 "+adapter.getCount());
//		for (int i = 0; i < adapter.getCount(); i++) {
//			try {
//				View listItem = adapter.getView(i, null, lv_tz_data);
//				listItem.measure(0, 0);
//				totalHeight += listItem.getMeasuredHeight();
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//
//		ViewGroup.LayoutParams params = lv_tz_data.getLayoutParams();
//		params.height = totalHeight
//				+ (lv_tz_data.getDividerHeight() * (adapter.getCount() - 1));
//		lv_tz_data.setLayoutParams(params);

		// 添加并且显示
		lv_tz_data.setAdapter(adapter);
		lv_tz_data.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getApplicationContext(),
						WeightNounExplainActivity.class);
				intent.putExtra("ItemName", ItemName[position]);
				intent.putExtra("position", position);
				startActivity(intent);

			}
		});

		dayTv = (TextView) findViewById(R.id.btn_wjk_detail_day);
		mounthTv = (TextView) findViewById(R.id.btn_wjk_detail_month);
		yearTv = (TextView) findViewById(R.id.btn_wjk_detail_year);
		weekTv = (TextView) findViewById(R.id.btn_wjk_detail_week);
		weekTv.setOnClickListener(this);
		mounthTv.setOnClickListener(this);
		yearTv.setOnClickListener(this);
		dayTv.setOnClickListener(this);
		rl_wjk_detail_back = (RelativeLayout) findViewById(R.id.rl_wjk_detail_back);
		rl_wjk_detail_back.setOnClickListener(this);
		setSelect(MyZxView.MODE_DAY);
	}

	/**
	 * 处理16进制数据
	 * 
	 * @param data
	 * @return
	 */
	private float getdata(byte... data) {
		BigInteger bigNum = new BigInteger(data);
		float intNum = Float.parseFloat(bigNum.intValue() + "");
		return intNum;
	}

	/**
	 * 水平显示详情
	 */
//	private void chartDetail() {
//		Intent intent = new WjkChart().execute(mContext);
//		mContext.startActivity(intent);
//	}

	/**
	 * 创建健康计划
	 */
	// private void createPlan(){
	// btnCreatePlan.setBackgroundDrawable(getResources().getDrawable(R.drawable.wjk_btn_cjjkjh_pressed));
	// Intent intent = new Intent(this,PlanWeightActivity.class);
	// startActivity(intent);
	// }

	/**
	 * share事件，弹出popupWindow
	 */
	// private SharePopWindow window;

	// private void sharePop() {
	// // 实例化SelectPicPopupWindow
	// window = new SharePopWindow(this, itemsOnClick);
	// // 显示窗口
	// window.showAtLocation(this.findViewById(R.id.ll_wjk_detail), //
	// 当前最外层的布局id
	// Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //
	// 设置layout在PopupWindow中显示的位置
	// }

	private WeightDataDao weightDataDao; // 体重秤表dao；

	private void initDAO() {
		BaseDao baseDao = BaseDao.getInstance(WjkDetailActivity.this);
		weightDataDao = baseDao.getWeightDataDao();
	}

	/**
	 * 获得一天的数据
	 * 
	 * @return
	 */
	private WeightData[] getDayAgoData() {
		WeightData[] weight;

		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.MILLISECOND, 0);
		Date date = cal.getTime();
		QueryBuilder<WeightData> qb = weightDataDao.queryBuilder();
		qb.where(Properties.User_id.eq(current_user.getUserid()));
		qb.orderAsc(Properties.Date);
		qb.where(Properties.Date.gt(date.getTime()));
		List<WeightData> datas = qb.list();
		for (WeightData te : datas) {
			Log.e("datas --time -- weight", new Date(te.getDate()).toString()
					+ te.getWeight());
		}
		weight = new WeightData[24];
		long weekDate = date.getTime();

		for (int i = 0; i < datas.size(); i++) {
			long curDate = datas.get(i).getDate();
			int temp = (int) (curDate - weekDate) / (1000 * 60 * 60);
			Log.e("temp---", temp + "");
			cal.setTimeInMillis(weekDate);
			Log.e("date", cal.get(Calendar.DATE) + "");
			Log.e("temp", temp + "");
			Log.e("iiiiii", i + "");
			if (temp < weight.length && temp >= 0)
				weight[temp] = datas.get(i);
		}
		return weight;
	}

	/**
	 * 获取一周以内的数据
	 * 
	 * @return
	 */
	private WeightData[] getWeekAgoData() {

		WeightData[] weight = new WeightData[7];

		Calendar curr = Calendar.getInstance();
		curr.set(Calendar.HOUR_OF_DAY, 0);
		curr.set(Calendar.MINUTE, 0);
		curr.set(Calendar.DAY_OF_MONTH, curr.get(Calendar.DAY_OF_MONTH) - 6);
		Date date = curr.getTime();
		QueryBuilder<WeightData> qb = weightDataDao.queryBuilder();
		qb.where(Properties.User_id.eq(current_user.getUserid()));
		qb.orderAsc(Properties.Date);
		qb.where(Properties.Date.gt(date.getTime()));
		List<WeightData> datas = qb.list();
		long weekDate = date.getTime();
		Calendar current_calendar = Calendar.getInstance();
		Calendar temp_calendar = Calendar.getInstance();
		int current_year = current_calendar.get(Calendar.YEAR);
		for (int i = 0; i < datas.size(); i++) {
			long curDate = datas.get(i).getDate();
			temp_calendar.setTimeInMillis(curDate);
			int temp_year = temp_calendar.get(Calendar.YEAR);
			int temp = -1;
			if(temp_year == current_year){
				temp = current_calendar.get(Calendar.DAY_OF_YEAR) - temp_calendar.get(Calendar.DAY_OF_YEAR);
			}else {
				temp = current_calendar.get(Calendar.DAY_OF_YEAR) + 31 - temp_calendar.get(Calendar.DATE);
			}
//			int temp = (int) (curDate - weekDate) / 86400000;
			if (temp >= 0 && temp < weight.length)
				weight[temp] = datas.get(i);
		}
		return weight;
	}

	/**
	 * 获取一个月以内的数据
	 * 
	 * @return
	 */
	private WeightData[] getMonthAgoData() {
		WeightData[] weight = new WeightData[31];

		Calendar curr = Calendar.getInstance();
		curr.set(Calendar.MONTH, curr.get(Calendar.MONTH) - 1);
		Date date = curr.getTime();
		QueryBuilder<WeightData> qb = weightDataDao.queryBuilder();
		qb.where(Properties.User_id.eq(current_user.getUserid()));
		qb.where(Properties.Date.gt(date.getTime()));
		List<WeightData> datas = qb.list();
		long weekDate = date.getTime();
		Calendar current_calendar = Calendar.getInstance();
		Calendar temp_calendar = Calendar.getInstance();
		int current_year = current_calendar.get(Calendar.YEAR);
		for (int i = 0; i < datas.size(); i++) {
			long curDate = datas.get(i).getDate();
			temp_calendar.setTimeInMillis(curDate);
			int temp_year = temp_calendar.get(Calendar.YEAR);
			int temp = -1;
			if(temp_year == current_year){
				temp = current_calendar.get(Calendar.DAY_OF_YEAR) - temp_calendar.get(Calendar.DAY_OF_YEAR);
			}else {
				temp = current_calendar.get(Calendar.DAY_OF_YEAR) + 31 - temp_calendar.get(Calendar.DATE);
			}
//			int temp = (int) (curDate - weekDate) / 86400000;
			if (temp >= 0 && temp < weight.length)
				weight[temp] = datas.get(i);
		}
		return weight;

	}

	/**
	 * 获取一年以内的数据
	 * 
	 * @return
	 */
	private WeightData[] getYearAgoData() {
		WeightData[] weight = new WeightData[12];

		Calendar c = Calendar.getInstance();
		c.add(Calendar.YEAR, -1);
		Date date = c.getTime();
		System.out.println(date);
		QueryBuilder<WeightData> qb = weightDataDao.queryBuilder();
		qb.where(Properties.User_id.eq(current_user.getUserid()));
		qb.where(Properties.Date.gt(date.getTime()));
		List<WeightData> datas = qb.list();
		long weekDate = Calendar.getInstance().getTimeInMillis();
		for (int i = 0; i < datas.size(); i++) {
			long curDate = datas.get(i).getDate();
			int temp = (int) ((curDate - weekDate) / (86400 * 31*1000));
			if (temp >= 0 && temp < weight.length)
				weight[temp] = datas.get(i);
		}
		return weight;
	}

	/**
	 * 获取当前最小重量
	 */
	private float getMinWeight() {
		QueryBuilder<WeightData> qb = weightDataDao.queryBuilder();
		qb.where(Properties.User_id.eq(current_user.getUserid()));
		qb.orderAsc(Properties.Weight);
		List<WeightData> list = qb.list();
		if (list.size() > 0) {
			return list.get(0).getWeight();
		} else {
			return 0;
		}
	}

	/**
	 * 获取当前最小重量
	 */
	private float getMaxWeight() {
		QueryBuilder<WeightData> qb = weightDataDao.queryBuilder();
		qb.where(Properties.User_id.eq(current_user.getUserid()));
		qb.orderDesc(Properties.Weight);
		List<WeightData> list = qb.list();
		if (list.size() > 0) {
			return list.get(0).getWeight();
		} else {
			return 0;
		}
	}

	/**
	 * 获取最后一条数据；
	 */
	private float getLastData() {
		QueryBuilder<WeightData> qb = weightDataDao.queryBuilder();
		qb.where(Properties.User_id.eq(current_user.getUserid()));
		qb.orderDesc(Properties.Id);
		List<WeightData> list = qb.list();
		if (list != null && list.size() > 1) {
			return list.get(0).getWeight() - list.get(1).getWeight();
		} else {
			return 0;
		}
	}

	/**
	 * 获取最后一条
	 */
	/**
	 * 获取最后一条数据；
	 */
	private WeightData getLastWeightData() {
		QueryBuilder<WeightData> qb = weightDataDao.queryBuilder();
		qb.where(Properties.User_id.eq(current_user.getUserid()));
		qb.orderDesc(Properties.Id);
		List<WeightData> list = qb.list();
		if (list != null && list.size() > 0) {
			return list.get(0);
		} else {
			return null;
		}
	}


	@SuppressLint("ResourceAsColor")
	private void setSelect(int index) {

		Drawable tab_button = getResources().getDrawable(R.drawable.tab_button);
		Drawable tab_button_white = getResources().getDrawable(
				R.drawable.tab_button_white);
		int white = getResources().getColor(R.color.white);
		int light_black = getResources().getColor(R.color.light_black);
		switch (index) {
		case MyZxView.MODE_DAY:
			dayTv.setTextColor(white);
			weekTv.setTextColor(light_black);
			mounthTv.setTextColor(light_black);
			yearTv.setTextColor(light_black);
			dayTv.setBackgroundDrawable(tab_button);
			weekTv.setBackgroundDrawable(tab_button_white);
			mounthTv.setBackgroundDrawable(tab_button_white);
			yearTv.setBackgroundDrawable(tab_button_white);
			break;
		case MyZxView.MODE_MOUNTH:
			dayTv.setTextColor(light_black);
			weekTv.setTextColor(light_black);
			mounthTv.setTextColor(white);
			yearTv.setTextColor(light_black);
			dayTv.setBackgroundDrawable(tab_button_white);
			weekTv.setBackgroundDrawable(tab_button_white);
			mounthTv.setBackgroundDrawable(tab_button);
			yearTv.setBackgroundDrawable(tab_button_white);
			break;
		case MyZxView.MODE_WEEK:
			dayTv.setTextColor(light_black);
			weekTv.setTextColor(white);
			mounthTv.setTextColor(light_black);
			yearTv.setTextColor(light_black);
			dayTv.setBackgroundDrawable(tab_button_white);
			weekTv.setBackgroundDrawable(tab_button);
			mounthTv.setBackgroundDrawable(tab_button_white);
			yearTv.setBackgroundDrawable(tab_button_white);
			break;
		case MyZxView.MODE_YEAR:
			dayTv.setTextColor(light_black);
			weekTv.setTextColor(light_black);
			mounthTv.setTextColor(light_black);
			yearTv.setTextColor(white);
			dayTv.setBackgroundDrawable(tab_button_white);
			weekTv.setBackgroundDrawable(tab_button_white);
			mounthTv.setBackgroundDrawable(tab_button_white);
			yearTv.setBackgroundDrawable(tab_button);
			break;
		default:
			break;
		}
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.ll_wjk_detail_chart:
		case R.id.btn_wjk_detail_day:
			myZxView.setGaveWorth(getDayAgoData(), MyZxView.MODE_DAY);
			setSelect(MyZxView.MODE_DAY);
			break;
		case R.id.btn_wjk_detail_week:
			myZxView.setGaveWorth(getWeekAgoData(), MyZxView.MODE_WEEK);
			setSelect(MyZxView.MODE_WEEK);
			break;
		case R.id.btn_wjk_detail_month:
			myZxView.setGaveWorth(getMonthAgoData(), MyZxView.MODE_MOUNTH);
			setSelect(MyZxView.MODE_MOUNTH);
			break;
		case R.id.btn_wjk_detail_year:
			myZxView.setGaveWorth(getYearAgoData(), MyZxView.MODE_YEAR);
			setSelect(MyZxView.MODE_YEAR);
			break;
		// chartDetail();
		case R.id.rl_wjk_detail_back:

			WjkDetailActivity.this.finish();
			break;
		case R.id.tableline:
			GoINtoDetail();
			break;
		case R.id.tv_add_device:
			// 连接方法；
			MobclickAgent.onEvent(mContext, "A004");
//			if (app.getBloodPBleProvider() != null) {
//				app.getBloodPBleProvider().disconnect();
//			}
//			if (temp2 == 11) { // 有可能当前体重秤正在连接 ，所以再点击的时候要执行一个断开方法
//				weightScaleProvider.disconnect();
//			}
//			getContentResolver().notifyChange(ObserverConstants.CHANGE_WEIGHT,
//					null);
			ConnectedDevice blood_device = FileUtil.getBloodDevice();
				if(blood_device.isConnected()){
					Intent intent = new Intent(WjkConstant.CONNECT_WEIGHT_ACTION_DISCONNECT);
					sendBroadcast(intent);
				}else {
					Intent intent = new Intent(WjkConstant.CONNECT_WEIGHT_ACTION);
					sendBroadcast(intent);
				}
			MainApplication.finishSpeciall();
			break;
		}
	}

	private void GoINtoDetail() {
		float datas[];
		long dates[];
		WeightData[] temp = null;
		switch (myZxView.getMode()) {
		case MyZxView.MODE_DAY:
			temp = getDayAgoData();
			break;
		case MyZxView.MODE_MOUNTH:
			temp = getMonthAgoData();
			break;
		case MyZxView.MODE_WEEK:
			temp = getWeekAgoData();
			break;
		case MyZxView.MODE_YEAR:
			temp = getYearAgoData();
			break;

		default:
			break;
		}
		// <<<<<<< HEAD
		// if (temp != null && temp.length > 0) {
		// datas = new float[temp.length];
		// dates = new long[temp.length];
		// for (int i = 0; i < temp.length; i++) {
		// if (temp[i] == null || temp[i].getDate() == null
		// || temp[i].getWeight() == null)
		// continue;
		// dates[i] = temp[i].getDate().getTime();
		// datas[i] = temp[i].getWeight();
		// }
		// Intent intent = new Intent(this, WjkDataInfo.class);
		// intent.putExtra("weight", datas);
		// intent.putExtra("date", dates);
		// startActivity(intent);
		// } else {
		// =======
		// if(temp != null && temp.length>0){
		// ArrayList<WeightData> list = new ArrayList<WeightData>();
		// for(int i=0;i<temp.length;i++){
		// if(temp[i]==null || temp[i].getDate() ==null || temp[i].getWeight()
		// == null)
		// continue;
		// list.add(temp[i]);
		// }
		// // datas = new float[list.size()];
		// // dates = new long[list.size()];
		// // for(int i=0;i<list.size();i++){
		// // dates[i] = list.get(i).getDate().getTime();
		// // datas[i] = list.get(i).getWeight();
		// // }
		// Intent intent = new Intent(this,WjkDataInfo.class);
		// Bundle bundle = new Bundle();
		// intent.putExtra("weight", datas);
		// intent.putExtra("date", dates);
		// startActivity(intent);
		// // }else {
		// return;
		// }
		if (temp != null && temp.length > 0) {
			ArrayList<WeightData> list = new ArrayList<WeightData>();
			for (int i = 0; i < temp.length; i++) {
				if (temp[i] == null || temp[i].getDate() == null
						|| temp[i].getWeight() == null)
					continue;
				list.add(temp[i]);
			}
			Intent intent = new Intent(this, WjkDataInfo.class);
			intent.putParcelableArrayListExtra("data", list);
			startActivity(intent);
		} else {
			return;
		}

	}
}
